package cn.gok.front.interceptor;

import cn.gok.gok_mall.constUtil.ConstUtil;
import cn.gok.gok_mall.entity.User;
import cn.gok.gok_mall.responseData.ResultData;
import cn.hutool.system.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: chenfan
 * @Description:
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     *
     * preHandle 方法会在调用任意的Controller请求之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setCharacterEncoding("utf-8");

        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(ConstUtil.USER_INFO);

        if (userInfo == null){

            ResultData resultData = ResultData.fail("对不起，您还未登录，请登录后尝试");

            //将ResultData转成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(resultData);
            response.getWriter().println(jsonStr);

            return false;
        }
        return true;
    }
}
